<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>rcheli.club VBar Control Sync</title>
    <link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap.css">
    <style>
    .btn-link {
        cursor: pointer;
    }
    </style>
</head>

<body>
    <div class="container">
        <h1>
            <img src="images/logo.png" /> VBar Control Sync
        </h1>

        <div class="row">
            <div class="col col-xs-6">
                <h2>
                    VBar Control
                </h2>
                <div id="divVbcModels" style="display:none">
                    <h3>Models</h3>
                    <ul id="lstVbcModels">
                    </ul>
                </div>
                <div id="divVbcBatteries" style="display:none">
                    <h3>Batteries</h3>
                    <ul id="lstVbcBatteries">
                    </ul>
                </div>
                <div id="divVbcScreenshots" style="display:none">
                    <h3>Screenshots</h3>
                    <p>
                        <span class="btn-link folder" data-folder="c:/VControl/screenshot">Open Folder</span>
                    </p>    
                    <p>
                        <span class="btn-link">Delete all Screenshots</span>
                    </p>
                    <ul id="lstVbcScreenshots">
                    </ul>
                </div>
                <div id="divVbcUserscreens" style="display:none">
                    <h3>User screens</h3>
                    <p>
                        <span class="btn-link folder" data-folder="c:/VControl/userscreen">Open Folder</span>
                    </p>    
                    <ul id="lstVbcUserscreens">
                    </ul>
                </div>
                <div id="divVbcBackups" style="display:none">
                    <h3>Saved Configurations</h3>
                    <p>
                        <span class="btn-link folder" data-folder="c:/VControl/vbar">Open Folder</span>
                    </p>    
                    <ul id="lstVbcBackups">
                    </ul>
                </div>
            </div>
            <div class="col col-xs-6">
                <h2>rcheli.club</h2>
                <form>
                    <div class="form-group">
                        <label for="txtRchEmail">Email</label>
                        <input type="email" name="email" id="txtRchEmail" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label for="txtRchPassword">Password</label>
                        <input type="password" name="password" id="txtRchPassword" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label></label>
                        <input type="button" name="login" id="btnRchLogin" class="btn btn-primary" value="Login" />
                        <a href="http://rcheli.club" target="_blank" class="btn btn-default ">Open rcheli.club</a>
                    </div>
                </form>
                <div id="divRchPilot" style="display:none">
                    <h3>Pilot</h3>
                    <p>
                        <span id="spnPilot"></span>
                    </p>
                    <p>
                        <img id="imgPilot" />
                    </p>
                </div>
                <div id="divRchModels" style="display:none">
                    <h3>Models</h3>
                    <ul id="lstRchModels">
                    </ul>
                </div>
                <div id="divRchBatteries" style="display:none">
                    <h3>Batteries</h3>
                    <ul id="lstRchBatteries">
                    </ul>
                </div>
                <div id="divUpload" style="display:none">
                    <input type="button" id="btnUpload" value="Upload Flight Logs" class="btn btn-warning" />
                </div>
            </div>
        </div>
    </div>
</body>

<script>
    // You can also require other files to run in this process
    require('./renderer.js')
</script>
<script>window.$ = window.jQuery = require('./node_modules/jquery/dist/jquery.js');</script>
<script src="./node_modules/jquery/dist/jquery.js"></script>
<script>
        var fs = require('fs');

        var token;

        var Config = require('electron-config');
        var config = new Config();

        var vbcModels = [];
        var vbcBatteries = [];

        var rchModels = [];
        var rchBatteries = [];

        var vbcDrive = 'c:/VControl/';
        var rchServices = 'http://localhost:57714/';

        function log(message) {
            console.log(message);
        }

        function loadVbc() {
            log('Loading VBar Control');

            loadVbcModels();
            loadVbcBatteries();
            loadVbcScreenshots();
            loadVbcUserscreens();
            loadVbcBackups();
        }

        function loadVbcModels() {
            vbcModels.length = 0;

            var files = fs.readdirSync(vbcDrive + 'log');

            $('#lstVbcModels').empty();
            $('#divVbcModels').css('display', 'block');

            for (var i in files) {
                var file = files[i];
                log(file);

                var filename = vbcDrive + 'log/' + file;
                if (fs.statSync(filename).isDirectory()) {
                    var vbcModel = {};
                    vbcModel.name = file.replace('_', ' ');
                    vbcModel.folder = filename;
                    vbcModels.push(vbcModel);

                    $('#lstVbcModels').append('<li>' + vbcModel.name + ' (<span class="folder btn-link " data-folder="' + vbcModel.folder + '">Open Folder</span>)</li>');
                }
            }
        }

        function loadVbcBatteries() {
            $('#divVbcBatteries').css('display', 'none');
            vbcBatteries.length = 0;

            var folders = fs.readdirSync(vbcDrive + 'battery');

            for (var i in folders) {
                var folder = folders[i];
                log(folder);

                var filename = vbcDrive + 'battery/' + folder;
                if (fs.statSync(filename).isDirectory()) {
                    var vbcBattery = {};
                    vbcBattery.name = fs.readFileSync(filename + '/name', 'UTF-8');
                    vbcBattery.folder = filename;
                    vbcBatteries.push(vbcBattery);
                }
            }

            vbcBatteries.sort(function(a, b) {
                return a.name > b.name;
            });

            log(vbcBatteries.length);
            $('#divVbcBatteries').css('display', 'block');
            $('#lstVbcBatteries').empty();

            for (var i in vbcBatteries) {
                var vbcBattery = vbcBatteries[i];
                $('#lstVbcBatteries').append('<li>' + vbcBattery.name + ' (<span class="folder btn-link" data-folder="' + vbcBattery.folder + '">Open Folder</span>)</li>');
            }
        }

        function loadVbcScreenshots() {
            var files = fs.readdirSync(vbcDrive + 'screenshot');

            $('#lstVbcScreenshots').empty();
            $('#divVbcScreenshots').css('display', 'block');

            for (var i in files) {
                var file = files[i];
                log(file);

                var filename = vbcDrive + 'screenshot/' + file;
                if (!fs.statSync(filename).isDirectory()) {
                    var name = file;
                    $('#lstVbcScreenshots').append('<li>' + name + ' (<span class="file btn-link" data-file="' + filename + '">Open Image</span>)</li>');
                }
            }
        }

        function loadVbcUserscreens() {
            var files = fs.readdirSync(vbcDrive + 'userscreen');

            $('#lstVbcUserscreens').empty();
            $('#divVbcUserscreens').css('display', 'block');

            for (var i in files) {
                var file = files[i];
                log(file);

                var filename = vbcDrive + 'userscreen/' + file;
                if (!fs.statSync(filename).isDirectory()) {
                    var name = file;
                    $('#lstVbcUserscreens').append('<li>' + name + '</li>');
                }
            }
        }

        function loadVbcBackups() {
            var files = fs.readdirSync(vbcDrive + 'vbar');

            $('#lstVbcBackups').empty();
            $('#divVbcBackups').css('display', 'block');

            for (var i in files) {
                var file = files[i];
                log(file);

                var filename = vbcDrive + 'vbar/' + file;
                if (!fs.statSync(filename).isDirectory()) {
                    var name = file.replace('_', ' ');
                    $('#lstVbcBackups').append('<li>' + name + '</li>');
                }
            }
        }

        $('#btnRchLogin').click(function () {
            var email = $('#txtRchEmail').val();
            var password = $('#txtRchPassword').val();
            log(email + ', ' + password);

            config.set('RchEmail', email);
            config.set('RchPassword', password);

            var body = {
                grant_type: 'password',
                username: email,
                password: password
            };

            $.ajax({
                url: rchServices + 'token',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                data: body,
                complete: function (data) {
                    log('token complete');
                    token = data.responseJSON.access_token;
                    loadRchPilot();
                },
                error: function () {
                    log('token error');
                }
            });
        });

        function loadRchPilot() {
            log('getting pilot details');
            $.ajax({
                url: rchServices + 'api/pilots',
                type: 'GET',
                headers: {
                    'authorization': 'bearer ' + token
                },
                complete: function (data) {
                    log('complete');
                    var pilot = data.responseJSON;
                    $('#spnPilot').text(pilot.Name);
                    $('#imgPilot').attr('src', pilot.ImageUrl);
                    $('#divRchPilot').css('display', 'block');
                    $('#divUpload').css('display', 'block');
                    loadRchModels();
                    loadRchBatteries();
                },
                error: function () {
                    log('error');
                }
            });
        }

        function loadRchModels() {
            log('getting models');
            $('#lstRchModels').empty();
            rchModels.length = 0;

            $.ajax({
                url: rchServices + 'api/models',
                type: 'GET',
                headers: {
                    'authorization': 'bearer ' + token
                },
                complete: function (data) {
                    log('complete');
                    var models = data.responseJSON;
                    for(var i in models) {
                        log(i);

                        var model = models[i];

                        var rchModel = {};
                        rchModel.Name = model.Name;
                        rchModel.ModelId = model.ModelId;
                        rchModels.push(rchModel);

                        $('#lstRchModels').append('<li>' + model.Name + '</li>');
                        // $('#imgPilot').attr('src', pilot.ImageUrl);
                    }
                     $('#divRchModels').css('display', 'block');
                    // LoadRchModels();
                },
                error: function () {
                    log('error');
                }
            });
        }

        function loadRchBatteries() {
            log('getting batteries');
            $('#lstRchBatteries').empty();
            rchBatteries.length = 0;

            $.ajax({
                url: rchServices + 'api/batteries',
                type: 'GET',
                headers: {
                    'authorization': 'bearer ' + token
                },
                complete: function (data) {
                    log('complete');
                    var batteries = data.responseJSON;
                    for(var i in batteries) {
                        log(i);
                        var battery = batteries[i];

                        var rchBattery = {};
                        rchBattery.BatteryId = battery.BatteryId;
                        rchBattery.Name = battery.Name;
                        rchBatteries.push(rchBattery);

                        $('#lstRchBatteries').append('<li>' + battery.Name + '</li>');
                        // $('#imgPilot').attr('src', pilot.ImageUrl);
                    }
                     $('#divRchBatteries').css('display', 'block');
                    // LoadRchModels();
                },
                error: function () {
                    log('error');
                }
            });
        }

        $(document).on('click', '.folder', function() {
            var folder = 'start ' + $(this).data('folder');
            log('folder ' + folder);
            var exec = require('child_process').exec;
            exec(folder);
        });

        $(document).on('click', '.file', function() {
            var file = 'start ' + $(this).data('file');
            log('file ' + file);
            var exec = require('child_process').exec;
            exec(file);
        });

        var drivelist = require('drivelist');

        function startDriveWatch() {
            log('watching Drives');

            drivelist.list(function(error, drives) {
                for(var i in drives) {
                    var drive = drives[i];
                    log(drive.description);
                    if (drive.description.startsWith('VControl')) {
                        log('found it!');
                    }
                }
            });

            setTimeout(startDriveWatch, 5000);
        }

        $(document).ready(function() {
           $('#txtRchEmail').val(config.get('RchEmail'));
           $('#txtRchPassword').val(config.get('RchPassword'));

            //startDriveWatch();

            loadVbc();
        });

        $('#divUpload').click(function() {
            for (var i in vbcModels) {
                var vbcModel = vbcModels[i];

                log(vbcModel.folder);

                var rchModel = rchModels.find(x => x.name == vbcModel.Name);
                if (rchModel == undefined) {
                    log('rch Model not found.  Skipping');
                } else {
                    log('found model ' + rchModel.Name);

                    var files = fs.readdirSync(vbcModel.folder);
                    for(var x in files) {
                        var file = files[x];
                        if (file.endsWith('.log')) {
                            log(file);

                            // parse logs
                            var stDate;
                            var stTime;
                            var fnTime;

                            fs.readFileSync(vbcModel.folder + '/' + file).toString().split('\n').forEach(function(line){
                                if (line.startsWith('VBar Start')){
                                    log(line);
                                    stDate = line.split(' -- ')[2];
                                }
                                if (line.includes('Calibration Finished')){
                                    log(line);
                                    stDate = line.split(' -- ')[2];
                                }
                                if (line.includes('Motorswitch Motor On')){
                                    log(line);
                                    stTime = line.split(';')[0];
                                }
                                if (line.includes('Motorswitch Motor Off')){
                                    log(line);
                                    fnTime = line.split(';')[0];
                                }
                                if (line.startsWith('VPlane Logfile End')){
                                    log(line);
                                    stDate = line.split(' -- ')[2];
                                }
                            });

                            var stDateVals = stDate.split('.');
                            var stTimeVals = stTime.split(':');
                            var stDateTime = new Date(stDateVals[2], stDateVals[1] - 1, stDateVals[0], stTimeVals[0], stTimeVals[1], stTimeVals[2]);

                            var fnTimeVals = fnTime.split(':');
                            var fnDateTime = new Date(stDateVals[2], stDateVals[1] - 1, stDateVals[0], fnTimeVals[0], fnTimeVals[1], fnTimeVals[2]);

                            var ms = fnDateTime.getTime() - stDateTime.getTime();

                            var flight = {};
                            flight.Reference = file;
                            flight.ModelId = rchModel.ModelId;
                            flight.DateTime = stDateTime.toJSON();
                            flight.DurationS = ms / 1000;

                            $.ajax({
                                async: false,
                                url: rchServices + 'api/flights',
                                type: 'POST',
                                headers: {
                                    'authorization': 'bearer ' + token
                                },
                                data: flight,
                                success: function (data) {
                                    log('flight uploaded');
                                    var models = data.responseJSON;
                                },
                                error: function (e) {
                                    log('error');
                                }
                            });
                        }
                    }
                }
            }
        });
</script>

</html>